package at.com.vn.chess.servlet;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import at.com.vn.chess.bean.RoomBean;
import at.com.vn.chess.bean.UserBean;
import at.com.vn.chess.dao.RoomDao;
import at.com.vn.chess.entity.User;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	RoomBean lstRoom = new RoomBean();
	Logger logger;
	
	// accessing from ChatServlet
	ArrayList<User> userList = new ArrayList<User>();
	ServletContext context;
	String sessionId = "";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
		logger = Logger.getLogger( getClass() );
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			
			logger.info( "begin login precess" );

			HttpSession session = request.getSession(true);
			String destination;

			UserBean userBean = new UserBean();
			User userCheck = new User();
			userCheck.setUser_id(request.getParameter("un"));
			userCheck.setUser_password(request.getParameter("pw"));
			// Save input value when err
			session.setAttribute("inputUser", userCheck);

			// Get list login user from other servlet
			context = getServletConfig().getServletContext();
			userList = (ArrayList<User>) context.getAttribute("LoginUserList");
			if (userList == null || userList.size() == 0) {
				userList = new ArrayList<User>();
			}

			// Check login user
			User userValid = userBean.getUserValid(userCheck);
			if (userValid != null) {
				// Save value for next page
				session.setAttribute("currentSessionUser", userValid);

				// add login user to list
				userList.add(userValid);
				context.setAttribute("LoginUserList", userList);

				// Get room data from database to display next page
				RoomDao roomDao = new RoomDao();
				roomDao.beginTrans();
				lstRoom.setLstRoom(roomDao.findAllRoom());
				roomDao.closeTrans();

				// Build entity, bean
				request.setAttribute("lstRoomBean", lstRoom);

				// Save sessionID to check user close browser
				destination = "/pages/roomList.jsp"; // logged-in page
			}

			else {
				// Set value for session
				session.setAttribute("errMessage",
						"userId or password not available");
				destination = "/pages/login.jsp"; // error page
			}

			RequestDispatcher rd = getServletContext().getRequestDispatcher(
					destination);
			rd.forward(request, response);

		}

		catch (Throwable theException) {
			logger.error( theException.getStackTrace() );
			System.out.println(theException);
		}
	}

}
